//
//  AddressViewController.m
//  SXH
//
//  Created by Jack on 15/9/15.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "AddressViewController.h"
#import "AddressTableViewCell.h"
#import "AddAddressViewController.h"
#import "UserAddressEntity.h"
#import "OrderEnsureViewController.h"
#import "CommonService.h"
#import "YYAnimationIndicator.h"
#import "MZTimerLabel.h"

@interface AddressViewController ()<MZTimerLabelDelegate>
{
    YYAnimationIndicator *indicator;
    MZTimerLabel *timer;
}


@property (nonatomic, strong) IBOutlet UIButton *btnAdd;
@property (nonatomic, strong) NSMutableArray *mutableArrayAddress;
@property (nonatomic, strong) IBOutlet UITableView *tableViewAddress;

@end

@implementation AddressViewController
@synthesize btnAdd;
@synthesize mutableArrayAddress;
@synthesize tableViewAddress;
@synthesize orderEnsureViewController;
@synthesize userEntity;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //新增地址边框
    btnAdd.layer.cornerRadius = 5.0f; //圆角半径
    btnAdd.layer.masksToBounds = YES; //圆角
    btnAdd.layer.borderWidth = 0.5f; //边框宽度
    btnAdd.layer.borderColor = [[UIColor grayColor]CGColor]; //边框颜色
    
//    NSUserDefaults *address = [NSUserDefaults standardUserDefaults];
//    //可以用alloc 方法代替
//    mutableArrayAddress = [NSMutableArray arrayWithArray:[address objectForKey:@"AddressArray"]];
//
//    [tableViewAddress reloadData];
    
    mutableArrayAddress = [[NSMutableArray alloc]init];
    [self getAddressList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source
- (void)viewDidAppear:(BOOL)animated{
////    [self viewDidLoad];
//    NSUserDefaults *address = [NSUserDefaults standardUserDefaults];
//    //可以用alloc 方法代替
//    mutableArrayAddress = [NSMutableArray arrayWithArray:[address objectForKey:@"AddressArray"]];

    [tableViewAddress reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayAddress count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"AddressTableViewCell";
    AddressTableViewCell *cell = (AddressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"AddressTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
//    UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayAddress objectAtIndex:indexPath.row]];
    UserAddressEntity *addressEntity = [mutableArrayAddress objectAtIndex:indexPath.row];
    cell.name.text = addressEntity.addName;
    cell.phone.text = addressEntity.addPhone;
    cell.address.text = [NSString stringWithFormat:@"%@%@%@%@",addressEntity.pro_name,addressEntity.city_name,addressEntity.district,addressEntity.detailAddress];
    if([addressEntity.isDefault isEqualToString:@"1"]){
        cell.backgroundColor = [UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.0f];
    }
    cell.btnSelectAddress.tag = indexPath.row;
    cell.btnEditAddress.tag = indexPath.row;
    [cell.btnSelectAddress addTarget:self action:@selector(selectAddress:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnEditAddress addTarget:self action:@selector(editAddress:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
   }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 68;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayAddress objectAtIndex:indexPath.row]];
//    orderEnsureViewController.addName.text = addressEntity.addName;
//    orderEnsureViewController.addPhone.text = addressEntity.addPhone;
//    orderEnsureViewController.addressInfo.text = addressEntity.addressInfo;
//    //返回上一页
//    [self.navigationController popViewControllerAnimated:YES];
}
-(void)selectAddress:(UIButton *)btn{
//    UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayAddress objectAtIndex:btn.tag]];
    
    UserAddressEntity *addressEntity = [mutableArrayAddress objectAtIndex:btn.tag];
    orderEnsureViewController.addName.text = addressEntity.addName;
    orderEnsureViewController.addPhone.text = addressEntity.addPhone;
    orderEnsureViewController.addressInfo.text = [NSString stringWithFormat:@"%@%@%@%@",addressEntity.pro_name,addressEntity.city_name,addressEntity.district,addressEntity.detailAddress];
    orderEnsureViewController.addressID = addressEntity.ID;
    //返回上一页
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)editAddress:(UIButton *)btn{
//    UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayAddress objectAtIndex:btn.tag]];
    
    UserAddressEntity *addressEntity = [mutableArrayAddress objectAtIndex:btn.tag];
    AddAddressViewController *vc = [[AddAddressViewController alloc]init];
    vc.userAddressEntity = addressEntity;
    vc.cellIndex = btn.tag;
    [[self navigationController]pushViewController:vc animated:YES];
}

//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//    return YES;
//}
//
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        UserAddressEntity *addressEntity = [mutableArrayAddress objectAtIndex:indexPath.row];
//        [mutableArrayAddress removeObjectAtIndex:indexPath.row];
//        // Delete the row from the data source.
//        [tableViewAddress deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//
////        NSUserDefaults *address = [NSUserDefaults standardUserDefaults];
////        //记住要转换成不可变数组类型
////        NSArray * array = [NSArray arrayWithArray:mutableArrayAddress];
////        [address setObject:array forKey:@"AddressArray"];
//    }
//    else if (editingStyle == UITableViewCellEditingStyleInsert) {
//        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
//    }
//}

-(IBAction)btnAddAddress:(id)sender
{
    AddAddressViewController *vc = [[AddAddressViewController alloc]init];
    [[self navigationController]pushViewController:vc animated:YES];
}

- (void) getAddressList{
    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
    [indicator setLoadText:Loading_Text];
    [self.view addSubview:indicator];
    
    [indicator startAnimation];  //开始转动
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userEntity.userId, @"userid",nil];
    
    [service getNetWorkData:param
                       Path:USER_ADDRESS_GET
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array) {
                          UserAddressEntity *entity = [[UserAddressEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayAddress addObject:entity];
                      }
                      [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [tableViewAddress reloadData];
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      [indicator stopAnimationWithLoadText:LoadFail_Text withType:YES];
                  }];

}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AddressViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AddressViewController"];
}
@end
